package icu.xuyijie.mysecondspringboot.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import icu.xuyijie.mysecondspringboot.entity.Student;
import icu.xuyijie.mysecondspringboot.entity.Teacher;
import icu.xuyijie.mysecondspringboot.mapper.StudentMapper;
import icu.xuyijie.mysecondspringboot.mapper.TeacherMapper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 徐一杰
 * @date 2024/11/6 15:44
 * @description 学生相关操作
 */
@Slf4j
@RequestMapping("/student")
@Controller
public class StudentController {
    @Autowired
    private StudentMapper stuMapper;
    @Autowired
    private TeacherMapper teacherMapper;

    @GetMapping("/findAll")
    public String findAll(Model model, String name, String className, @RequestParam(defaultValue = "1") Integer pageNo) {
        try (Page<Student> page = PageMethod.startPage(pageNo, 5)) {
            // () -> 叫箭头函数，也叫 lambda 表达式
            PageInfo<Student> pageInfo = page.doSelectPageInfo(() -> stuMapper.findAll(name, className));

            List<Student> studentList = pageInfo.getList();

            // 2、把数据设置到页面上
            model.addAttribute("dataList", studentList);
            // 设置分页的总页数
            int pages = pageInfo.getPages();
            model.addAttribute("pageTotal", pages);
            // 设置当前页码
            model.addAttribute("pageNo", pageNo);
            List<Integer> pageList = new ArrayList<>();
            for (int i = 0; i < pages; i++) {
                pageList.add(i + 1);
            }
            model.addAttribute("pageList", pageList);
            // 3、跳转页面到 studentList.html
            return "studentList";
        }
    }

    @GetMapping("/deleteStudent")
    public String deleteStudent(Integer stuId) {
        // 删除数据
        stuMapper.deleteStudentById(stuId);

        // 重新加载页面数据
        return "redirect:/student/findAll";
    }

    @GetMapping("/goAddStudent")
    public String goAddStudent(Model model, Integer stuId) {
        // 新增按钮情况
        if (stuId == null) {
            model.addAttribute("student", new Student());
        } else {
            // 根据 id 查询数据信息
            Student studentById = stuMapper.findStudentById(stuId);
            model.addAttribute("student", studentById);
        }

        List<Teacher> teacherList = teacherMapper.findAll(new Teacher());
        model.addAttribute("teacherList", teacherList);

        return "addStudent";
    }

    @PostMapping("/saveStudent")
    public String saveStudent(Student student) {
        // 新增按钮情况
        if (student.getId() == null) {
            student.setCreateTime(new Date());
            stuMapper.inertStudent(student);
        } else {
            // 更新表单数据到数据库
            stuMapper.updateStudentById(student);
        }

        // 重新加载列表页
        return "redirect:/student/findAll";
    }

    @PostMapping("/upload")
    @Transactional(rollbackFor = Exception.class)
    public String upload(MultipartFile multipartFile, Integer id) throws IOException {
        String filename = multipartFile.getOriginalFilename();

        // 回滚
        Student student = new Student();
        student.setId(id);
        student.setImgUrl("http://127.0.0.1:8080/file/" + filename);
        stuMapper.updateStudentById(student);

        File file = new File("E:/uploadFiles/" + filename);
        multipartFile.transferTo(file);

        // 重新加载列表页
        return "redirect:/student/findAll";
    }

    @GetMapping("/output")
    public void output(HttpServletResponse response) throws IOException {
        // 告诉浏览器我这次给你的内容是一个 excel 文件
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        // 确保导出的文件内容的中文不会出现乱码
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("学生数据", StandardCharsets.UTF_8);

        // 确保浏览器的行为是下载而不是直接打开浏览
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 查询全部学生数据
        List<Student> studentList = stuMapper.findAll(null, null);

        // easyExcel 把数据放入 excel
        EasyExcelFactory
                // 写入响应流里面
                .write(response.getOutputStream(), Student.class)
                .sheet("sheet1")
                // 放入学生数据
                .doWrite(studentList);
    }

}
